package com.weixin.demo.rest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.weixin.demo.core.utils.InputStreamToStringUtils;
import com.weixin.demo.core.utils.Xml2JsonUtil;
import com.weixin.demo.model.EventRes;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/rest/wx/")
@Slf4j
public class WxMessageRest {

    /**
     * 微信回调接口
     */
    @RequestMapping(value = "/requestMessage", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity requestMessage(HttpServletRequest request, String signature, Long timestamp,
                                         Integer nonce, String echostr, String msg_signature) throws Exception {

        log.debug("#weixin.callback:GET----signature=" + signature + "----timestamp=" + timestamp + "----" +
                "nonce=" + nonce + "----echostr=" + echostr + "----msg_signature=" + msg_signature);

        InputStream is = request.getInputStream();
        String respData = InputStreamToStringUtils.streamToString(is);
        if (StringUtils.isNotBlank(respData)) {

            JSONObject jsonObject = Xml2JsonUtil.xml2Json(respData);

            log.info("#requestMessage.InputStream# respData:{}", JSON.toJSONString(jsonObject));

            String event = jsonObject.getString("Event");
            String openId = jsonObject.getString("FromUserName");
            String eventKey = jsonObject.getString("EventKey");
            String toUserName = jsonObject.getString("ToUserName");

            log.info("#requestMessage# event=" + event + "-------openId=" + openId + "-----------toUserName=" + toUserName);
            String msgType = jsonObject.getString("MsgType");

            switch (msgType) {
                case "text":
//                    echostr = wxOffiaccountService.msgReply(jsonObject);
                    break;
                case "event":
                    switch (event) {
                        case "SCAN":
                            log.debug("#requestMessage#--->SCAN");
                            EventRes focus = focusOnEvent(jsonObject);
                            //处理逻辑

                            break;
                        case "subscribe":
                            log.debug("#requestMessage#--->subscribe");
                            EventRes subscribe = subscribeEvent(jsonObject);
                            //处理逻辑

                            break;
                        default:
                            break;
                    }
                default:
                    break;
            }
        }
        log.info("response to wx is " + echostr);
        return new ResponseEntity(echostr, HttpStatus.OK);
    }


    /**
     * 微信回调接口
     */
    @RequestMapping(value = "/requestMessage.json", method = {RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity requestMessageJson(HttpServletRequest request, String signature, Long timestamp,
                                             Integer nonce, String echostr, String msg_signature) throws Exception {

        log.debug("-------weixin.callback:GET----signature=" + signature + "----timestamp=" + timestamp + "----" +
                "nonce=" + nonce + "----echostr=" + echostr + "----msg_signature=" + msg_signature);

        InputStream is = request.getInputStream();
        String respData = InputStreamToStringUtils.streamToString(is);
        if (StringUtils.isNotBlank(respData)) {
            JSONObject jsonObject = Xml2JsonUtil.xml2Json(respData);
            log.info(JSON.toJSONString(jsonObject));
            String event = jsonObject.getString("Event");
            String openId = jsonObject.getString("FromUserName");
            String eventKey = jsonObject.getString("EventKey");
            String toUserName = jsonObject.getString("ToUserName");

            log.debug("-------------------event=" + event + "-------openId=" + openId + "-----------toUserName=" + toUserName);

            String msgType = jsonObject.getString("MsgType");
            switch (msgType) {
                case "text":
//                    echostr = wxOffiaccountService.msgReply(jsonObject);
                    break;
                case "event":
                    switch (event) {
                        case "SCAN":
                            log.debug("requestMessage--->SCAN");
                            EventRes focus = focusOnEvent(jsonObject);

                            break;
                        case "subscribe":
                            log.debug("requestMessage--->关注事件");
                            EventRes subscribe = subscribeEvent(jsonObject);

                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        }
        log.debug("response to wx is " + echostr);
        return new ResponseEntity(echostr, HttpStatus.OK);
    }


    /**
     * 用户已关注时，扫码后的事件推送
     */
    private EventRes focusOnEvent(JSONObject jsonObject) throws Exception {

        String openId = jsonObject.getString("FromUserName");
        String eventKey = jsonObject.getString("EventKey");

        log.debug("[focusOnEvent] 扫码后的事件推送={} openId={} eventKey={}", jsonObject.toJSONString(), openId, eventKey);

        if (StringUtils.isBlank(eventKey) || StringUtils.isBlank(openId)) {
            return null;
        }

        eventKey = eventKey.replace("qrscene_", "");
        String[] eventKeyArray = eventKey.split("_");
        String switchKey = eventKeyArray[0];
        switch (switchKey) {
            case "Login": //登录扫码
                log.debug("扫码登录:", openId);


                return new EventRes(EventRes.Event.LOGIN, null);
            case "Bonding"://绑定扫码
                log.debug("扫码绑定:{}", openId);

                return new EventRes(EventRes.Event.BONDING, null);

            default:
                break;
        }
        return null;
    }

    /**
     * 关注事件
     */
    private EventRes subscribeEvent(JSONObject jsonObject) throws Exception {

        String openId = jsonObject.getString("FromUserName");
        String eventKey = jsonObject.getString("EventKey");
        log.debug("[subscribeEvent] 关注事件={} openId={} eventKey={}", jsonObject.toJSONString(), openId, eventKey);

        if (StringUtils.isBlank(openId)) {
            return null;
        }
        //如果eventKey为空，代表此次请求为用户只是关注公众号。
        if (StringUtils.isBlank(eventKey)) {

            return new EventRes(EventRes.Event.ATTENTION, null);
        }
        eventKey = eventKey.replace("qrscene_", "");
        String[] eventKeyArray = eventKey.split("_");
        String switchKey = eventKeyArray[0];
        switch (switchKey) {
            case "Login": //登录扫码

                return new EventRes(EventRes.Event.LOGIN, null);
            case "Bonding"://绑定扫码

                return new EventRes(EventRes.Event.BONDING, null);
        }
        return null;
    }

    /**
     * 微信授权回调，然后根据回调code获取微信access_Token,再根据access_Token拉取微信用户数据，回写到数据库后，
     * 根据用户id调用 教研云接口，登录获取票据信息，然后再进行重定向操作
     *
     * @return
     */
    @RequestMapping(value = "/wxAuthCallback", method = {RequestMethod.GET, RequestMethod.POST})
    public void wxAuthCallback(HttpServletRequest request, HttpSession session, HttpServletResponse response) {
        try {
            long starttime = System.currentTimeMillis();
            String code = request.getParameter("code");
            String state = request.getParameter("state");
            String page = request.getParameter("page");


        } catch (Exception e) {
            String msg = "用户分享认证失败";
            log.error(e.getMessage(), e);
        }
    }


    public static void main(String[] args) {

        log.info("ss");
    }
}
